<template>
  <el-dialog
    v-model="localVisible"
    title="全局搜索"
    width="600px"
    :show-close="false"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    custom-class="quick-search-dialog"
    @closed="handleClosed"
  >
    <!-- 搜索输入框 -->
    <div class="search-container">
      <el-input
        ref="searchInputRef"
        v-model="searchQuery"
        placeholder="搜索..."
        size="large"
        clearable
        @input="handleSearchInput"
        @keydown.down="moveSelection(1)"
        @keydown.up="moveSelection(-1)"
        @keydown.enter="selectItem"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 搜索结果列表 -->
    <div class="search-results" v-if="searchResults.length > 0">
      <div
        v-for="(item, index) in searchResults"
        :key="item.id"
        class="result-item"
        :class="{ 'is-active': selectedIndex === index }"
        @click="selectItem(item)"
        @mouseenter="selectedIndex = index"
      >
        <div class="result-icon">
          <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
        </div>
        <div class="result-content">
          <div class="result-title">{{ item.title }}</div>
          <div class="result-description" v-if="item.description">
            {{ item.description }}
          </div>
        </div>
      </div>
    </div>

    <!-- 无结果状态 -->
    <div class="no-results" v-else-if="searchQuery && searchPerformed">
      没有找到匹配的结果
    </div>

    <!-- 底部操作提示 -->
    <template #footer>
      <div class="quick-tips">
        <div class="tip-item" v-for="tip in quickTips" :key="tip.text">
          <span class="tip-key">{{ tip.key }}</span>
          <span class="tip-text">{{ tip.text }}</span>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { Search, Document, Setting, User, Goods } from '@element-plus/icons-vue'
import { getSearchAPI } from '@/apis/search'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'select', 'close'])

// 搜索状态
const localVisible = ref(false)
const searchQuery = ref('')
const searchResults = ref([])
const selectedIndex = ref(-1)
const searchPerformed = ref(false)
const searchInputRef = ref(null)

// 同步父组件传入的 visible 状态
watch(() => props.modelValue, (val) => {
  localVisible.value = val
  if (val) {
    nextTick(() => {
      searchInputRef.value?.focus()
    })
  }
})

// 同步本地 visible 状态到父组件
watch(localVisible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    emit('close')
  }
})

// 模拟数据
const mockData = ref([
  { id: 1, title: '用户管理', description: '管理系统用户账户', icon: User },
  { id: 2, title: '商品管理', description: '管理商品和库存', icon: Goods },
  { id: 3, title: '系统设置', description: '配置系统参数', icon: Setting },
  { id: 4, title: '文档中心', description: '查看系统使用文档', icon: Document },
])

// 快速提示
const quickTips = ref([
  { key: '↑↓', text: '导航' },
  { key: '↵', text: '选择' },
  { key: 'esc', text: '关闭' }
])

// 处理搜索输入
const handleSearchInput = async () => {
  if (!searchQuery.value.trim()) {
    searchResults.value = []
    searchPerformed.value = false
    return
  }

  // 接口搜索
  // const param = {
  //   keyword: searchQuery.value,
  // }
  // const res = await getSearchAPI(param)
  // if (res.code !== 200) {
  //   mockData.value = res.result.conditions.brands
  // } else {
  //   ElMessage.error(res.msg || '搜索失败')
  //   // return
  // }

  // 模拟搜索延迟
  setTimeout(() => {
    searchResults.value = mockData.value.filter(item =>
      item.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      item.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
    searchPerformed.value = true
    selectedIndex.value = searchResults.value.length > 0 ? 0 : -1
  }, 150)
}

// 移动选择项
const moveSelection = (direction) => {
  if (searchResults.value.length === 0) return

  selectedIndex.value += direction

  // 边界检查
  if (selectedIndex.value < 0) {
    selectedIndex.value = searchResults.value.length - 1
  } else if (selectedIndex.value >= searchResults.value.length) {
    selectedIndex.value = 0
  }
}

// 选择项目
const selectItem = (item) => {
  const selectedItem = item || searchResults.value[selectedIndex.value]
  if (!selectedItem) return

  emit('select', selectedItem)
  localVisible.value = false
}

// 关闭处理
const handleClosed = () => {
  searchQuery.value = ''
  searchResults.value = []
  selectedIndex.value = -1
  searchPerformed.value = false
}
</script>

<style scoped>
/* 保持之前的样式不变 */
.search-container {
  margin-bottom: 16px;
}

.search-results {
  max-height: 400px;
  overflow-y: auto;
  margin-top: 8px;
  border-radius: var(--el-border-radius-base);
  border: 1px solid var(--el-border-color-light);
}

.result-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.result-item:hover,
.result-item.is-active {
  background-color: var(--el-fill-color-light);
}

.result-icon {
  margin-right: 12px;
  color: var(--el-text-color-secondary);
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.result-description {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.no-results {
  text-align: center;
  padding: 24px;
  color: var(--el-text-color-secondary);
}

.quick-tips {
  display: flex;
  justify-content: center;
  gap: 24px;
  padding: 16px;
  border-top: 1px solid var(--el-border-color-light);
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.tip-key {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: var(--el-fill-color);
  color: var(--el-text-color-secondary);
}

.tip-text {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
</style>
